package com.hwy.widget.drag_list

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.hwy.widget.R
import com.hwy.widget.decoration.CommonDecoration
import com.hwy.widget.utils.DisplayUtil
import com.hwy.widget.widget.SimpleTextWatcher
import java.util.*
import kotlin.collections.ArrayList

/**
 * RecyclerView 拖拽排序的实现方案
 */
class DragSortActivity : AppCompatActivity(), IDragCallback {

    companion object {
        private const val TAG = "DragSortActivity"
    }

    private var recyclerView: RecyclerView? = null

    private var itemTouchHelper: ItemTouchHelper? = null

    private val dataList by lazy {
        ArrayList<String>().apply {
            add("美团")
            add("腾讯控股")
            add("阿里巴巴-SW")
            add("小米集团-W")
            add("快手-W")
            add("中兴通讯")
            add("中国恒大")
            add("融创中国")
            add("中铝国际")
            add("农夫山泉")
            add("信达生物")
            add("中芯国际")
            add("中国移动")
            add("京东集团")
            add("商汤-W")
            add("中国平安")
            add("恒大汽车")
            add("吉利汽车")
            add("华润置地")
            add("碧桂园")
            add("汇通达网络")
            add("紫荆矿业")
            add("江山集团")
            add("裕田中国")
            add("万嘉集团")
            add("中科生物")
            add("首钢资源")
            add("中国华星")
            add("金汇教育")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_drag_sort)

        recyclerView = findViewById<RecyclerView>(R.id.recycler_view)?.apply {
            layoutManager = GridLayoutManager(context, 1)
//            layoutManager = LinearLayoutManager(context)
            addItemDecoration(
                CommonDecoration(
                    context,
                    DisplayUtil.dpToPx(4),
                    ColorDrawable(Color.WHITE)
                )
            )
            adapter = DragSortAdapter()

            RecyclerDragCallback(this@DragSortActivity).run {
                itemTouchHelper = ItemTouchHelper(this)
                itemTouchHelper?.attachToRecyclerView(this@apply)
            }
        }

        findViewById<EditText>(R.id.et_column)?.run {
            addTextChangedListener(object : SimpleTextWatcher() {
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

                    (recyclerView?.layoutManager as? GridLayoutManager)?.run {
                        spanCount = try {
                            val column = s?.toString()?.toInt() ?: 1
                            if (column > 0) {
                                column
                            } else {
                                1
                            }
                        } catch (e: NumberFormatException) {
                            Log.d(TAG, "column format exception")
                            1
                        }
                        recyclerView?.adapter?.notifyDataSetChanged()
                    }
                }
            })
        }

    }

    private inner class DragSortAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return DragSortViewHolder(
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.layout_sort_drag_adapter, parent, false)
            )
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            (holder as? DragSortViewHolder)?.bindView(position, dataList[position])
        }

        override fun getItemCount(): Int {
            return dataList.size
        }

    }

    private inner class DragSortViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bindView(position: Int, data: String) {

            itemView.findViewById<TextView>(R.id.tv_drag_item)?.run {
                text = data
                setBackgroundColor(resources.getColor(R.color.color_gray_c))
            }

            itemView.findViewById<ImageView>(R.id.iv_drag)?.run {
                // 设置触摸拖拽
                setOnTouchListener { _, event ->

                    if (position < 3) {
                        // 禁止前三个数据触摸排序
                        return@setOnTouchListener false
                    }

                    if (event.actionMasked == MotionEvent.ACTION_DOWN) {
                        itemTouchHelper?.startDrag(this@DragSortViewHolder)
                    }
                    return@setOnTouchListener false
                }
            }

        }

    }

    override fun onItemMove(fromPosition: Int, toPosition: Int): Boolean {

        if (toPosition < 3) {
            // 禁止前三个数据参与排序
            return false
        }

        Collections.swap(dataList, fromPosition, toPosition)
        recyclerView?.adapter?.run {
            notifyItemMoved(fromPosition, toPosition)
            Log.d("TAG", "convert from = ${fromPosition}, to = ${toPosition}")
        }

        return true
    }

    override fun onItemDismiss(position: Int) {

        dataList.removeAt(position)
        recyclerView?.adapter?.notifyItemRemoved(position)

    }

    override fun onItemSelected(position: Int?) {

        position?.run {
            recyclerView?.findViewHolderForAdapterPosition(this)?.run {
                itemView?.findViewById<TextView>(R.id.tv_drag_item)?.run {
                    setBackgroundColor(resources.getColor(R.color.color_gray_9))
                }
            }
        }

    }

    override fun onItemClear(position: Int) {
        recyclerView?.findViewHolderForAdapterPosition(position)?.run {
            itemView?.findViewById<TextView>(R.id.tv_drag_item)?.run {
                setBackgroundColor(resources.getColor(R.color.color_gray_c))
            }
        }
    }

}